package com.zlb.app.modules.auth.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlb.app.modules.auth.entity.UserInfo;
import com.zlb.app.modules.auth.entity.vo.LoginVO;
import com.zlb.app.modules.auth.service.IAuthService;
import com.zlb.app.modules.auth.service.IUserInfoService;
import com.zlb.app.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Desc 认证相关接口实现
 * @Author zWX1367238
 * @Date 2024-09-05 14:48:08
 **/
@Service
public class AuthServiceImpl implements IAuthService {

    @Autowired
    private IUserInfoService userService;

    @Override
    public Object login(LoginVO loginVO) {
        Date now = new Date();
        String userName = loginVO.getUserName();
        String password = loginVO.getPassword();
        Assert.isNull(userName, "用户名不能为空!");
        Assert.isNull(password, "密码不能为空!");
        UserInfo user = userService.getOne(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserName, userName).last("limit 1"));
        Assert.isNull(user, "用户不存在,请注册后登录!");
        Assert.isTrue(user.getStatus() == 1, "该账户已被禁用!");
        Assert.isTrue(!SaSecureUtil.md5(password).equals(user.getPassword()), "密码不正确!");
        Long id = user.getId();
        Assert.isTrue(StpUtil.isLogin(id), "您已登录,请勿重复登录!");
        StpUtil.login(id);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        user.setLoginEndTime(now);
        userService.updateById(user);
        return tokenInfo;
    }

}
